import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/6/22 19:36
 * 启动类
 */
@SuppressWarnings({"all"})
public class App {

    // 演示使用 xml 文件的方式获取 bean
    public static void main01(String[] args) {
        // 1. 先得到 Spring 对象
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-config.xml");
        // 2. 从 Spring 中取出对象
        Student student1 = (Student) context.getBean("student");  // 根据 bean id 获取(bean 名称)
        Student student2 = context.getBean(Student.class);  // 根据 class 获取(bean 类型)
        Student student3 = context.getBean("student", Student.class);  // 主流方式, 不存在则返回 null
        // 3. 使用对象
        student1.sayHello();
        student2.sayHello();
        student3.sayHello();
        System.out.println("student1 == student2 ? " + (student1 == student2));  // 同一对象
        System.out.println("student2 == student3 ? " + (student2 == student3));  // 同一对象
    }

    // 演示使用 BeanFactory 的方式获取 bean(老式方法, 不推荐！！！)
    public static void main02(String[] args) {
        // 1. 先得到 Spring 对象
        // ！！！相较 ApplicationContext 是需要的时候才加载对应的 bean
        BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("spring-config.xml"));
        // 2. 从 Spring 中取出对象
        Student student1 = (Student) beanFactory.getBean("student");  // 根据 bean id 获取(bean 名称)
        Student student2 = beanFactory.getBean(Student.class);  // 根据 class 获取(bean 类型)
        Student student3 = beanFactory.getBean("student", Student.class);  // 主流方式, 不存在则返回 null
        // 3. 使用对象
        student1.sayHello();
        student2.sayHello();
        student3.sayHello();
        System.out.println("student1 == student2 ? " + (student1 == student2));  // 同一对象
        System.out.println("student2 == student3 ? " + (student2 == student3));  // 同一对象
    }
}
